package com.ly.blog_common.base;

import com.ly.blog_common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 覆盖系统的 error 定制化处理 + ControllerAdvice 解决异常定制返回
 * @author ly create at 2021/6/6 - 7:21
 **/
@Slf4j
@RestController
public class GlobalSystemErrorContoller {

    @Autowired
    private BasicErrorController basicErrorController;

    @RequestMapping(value = "/error", method = {RequestMethod.GET, RequestMethod.POST})
    public R error(HttpServletRequest request, HttpServletResponse response) {
        //定义为正常返回
        response.setStatus(HttpStatus.OK.value());

        //获取异常返回
        ResponseEntity<Map<String, Object>> errorDetail = basicErrorController.error(request);
        errorDetail.getBody().get("path");
        errorDetail.getBody().get("timestamp");
        log.error("【系统异常】 - status：{}，message：{}，path：{}，timestamp：{}"
                , errorDetail.getBody().get("status")
                , errorDetail.getBody().get("message")
                , errorDetail.getBody().get("path")
                , errorDetail.getBody().get("timestamp")
        );

        //自定义错误码对应信息发返回
        String message;
        Integer code = (Integer) errorDetail.getBody().get("status");
        switch (code) {
            case 403:
                message = "用户没有访问权限，"+errorDetail.getBody().get("message").toString();
                break;
            default:
                message = errorDetail.getBody().get("message").toString();
        }
        ;


        //自行组织返回数据
        return R.error(Integer.parseInt(code.toString()), message);

    }

}
